package com.kehao.leetcode.middle.math;

import org.junit.Test;

import java.util.*;

public class FractionToDecimalSolution {
    public String fractionToDecimal(int a, int b) {
        long numerator =a; long denominator = b;
        StringBuffer sb = new StringBuffer();
        String sign = (numerator>0)^(denominator>0)?"-":"";
        if(numerator==0) return "0";
        sb.append(sign);
        if(numerator>0) numerator = -numerator;
        if(denominator>0) denominator = -denominator;
        sb.append(numerator/denominator);
        if(numerator%denominator==0) {
            return sb.toString();
        }
        sb.append(".");

        numerator = numerator%denominator;
        numerator*=10;
        HashMap<Long,Integer> circleIndexMap = new HashMap<>();
        while (numerator!=0&& !circleIndexMap.containsKey(numerator)){
            sb.append(numerator/denominator);
            circleIndexMap.put(numerator,sb.length()-1);
            numerator = numerator%denominator;
            numerator*=10;
        }

        if(numerator!=0){
            sb.insert(circleIndexMap.get(numerator),"(");
            sb.append(")");
        }

        return sb.toString();

    }



    @Test
    public void test01(){
//        System.out.println(fractionToDecimal(1, 2));
//        System.out.println(fractionToDecimal(2, 1));
//        System.out.println(fractionToDecimal(2, 3));
//        System.out.println(fractionToDecimal(4, 333));
//        System.out.println(fractionToDecimal(1, 5));
//        System.out.println(fractionToDecimal(1, 90));
//        System.out.println(fractionToDecimal(1, 333));
//        System.out.println(fractionToDecimal(-50, 8));
        System.out.println(fractionToDecimal(-1, -2147483648));
    }
}
